import 'dart:math' as math;

import 'package:flutter/material.dart';

class RotateAnimation extends StatefulWidget {
  final Curve curve;

  // -1到1 代表-360度到360度
  final double beginRotate;

  // -1到1 代表-360度到360度
  final double endRotate;

  final double? beginOpacity;

  final Widget? child;

  final bool autoStart;

  final Duration? duration;

  final Duration? delayDuration;

  final Function(AnimationController controller)? onCreateController;

  const RotateAnimation({
    super.key,
    this.curve = Curves.fastOutSlowIn,
    this.beginRotate = -0.5,
    this.endRotate = 0.0,
    this.beginOpacity,
    this.child,
    this.autoStart = true,
    this.duration = const Duration(milliseconds: 2000),
    this.delayDuration,
    this.onCreateController,
  });

  @override
  State<StatefulWidget> createState() {
    return _RotateAnimationState();
  }
}

class _RotateAnimationState extends State<RotateAnimation>
    with TickerProviderStateMixin {
  late final AnimationController controller;

  late final Animation<double> rotate;
  late final Animation<double> opacity;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    );
    rotate = Tween(
      begin: widget.beginRotate * math.pi * 2,
      end: widget.endRotate * math.pi * 2,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Interval(
          0,
          1,
          curve: widget.curve,
        ),
      ),
    );
    opacity = Tween(
      begin: widget.beginOpacity ?? 1,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Interval(
          0,
          1,
          curve: widget.curve,
        ),
      ),
    );
    if (widget.autoStart) {
      Future.delayed(widget.delayDuration ?? const Duration()).then((value) {
        controller.forward();
      });
    }
    widget.onCreateController?.call(controller);
  }

  @override
  dispose() {
    controller.stop();
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      builder: (BuildContext context, child) {
        return Transform.rotate(
          angle: rotate.value,
          child: Opacity(
            opacity: opacity.value,
            child: widget.child,
          ),
        );
      },
      animation: controller,
    );
  }
}
